/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package fuzzy.actions;

import fuzzy.hibernate.HibernateUtil;
import fuzzy.hibernate.Klienci;
import fuzzy.hibernate.Uzytkownicy;
import fuzzy.tools.Tools;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionRedirect;
import org.apache.struts.actions.DispatchAction;
import org.hibernate.Query;
import org.hibernate.Session;

/**
 *
 * @author michal
 */
public class ClientAction extends DispatchAction {

    /* forward name="success" path="" */
    private final static String SUCCESS = "success";

    public ActionForward list(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        Uzytkownicy loggedUser = (Uzytkownicy) request.getSession().getAttribute("user");
        if (loggedUser == null || !loggedUser.isUserInRole("admin")) {
            response.sendError(403, "Access Denied");
        }
        
        Session currentSession = HibernateUtil.getSession();
        currentSession.beginTransaction();
        
        // Pobieramy wszystkich klientów z bazy.
        Query q = currentSession.createQuery("FROM Klienci ORDER BY idKlienta");
        List<Klienci> klienci = q.list();
        List<ClientActionForm> clients = new ArrayList();
        
        // Tworzymy obiekty beana ClientActionForm.
        for (Klienci klient: klienci) {
            ClientActionForm client = new ClientActionForm();
            client.setClientId(klient.getIdklienta());
            client.setFirstname(klient.getImie());
            client.setLastname(klient.getNazwisko());
            client.setPesel(klient.getPesel());
            client.setAddress(klient.getAdres());
            clients.add(client);
        }
        
        request.setAttribute("clients", clients);
        
        return mapping.findForward("list");
    }
    
    public ActionForward manage(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        int clientId = Tools.getClientId(request.getParameter("clientId"));
        Uzytkownicy loggedUser = Tools.getUser(request);
        
        if (!loggedUser.isUserInRole("admin") && (!loggedUser.isUserInRole("anonim") && clientId > 0)) {
            response.sendError(403, "Access Denied");
        }
        
        ClientActionForm clientBean = (ClientActionForm) form; // Dane z formularza.
        
        Klienci client;
        Uzytkownicy user;
        
        Session currentSession = HibernateUtil.getSession();
        currentSession.beginTransaction();
        
        // Sprawdzamy, czy użytkownik chce edytować dane klienta.
        if (clientId > 0) {
            Query q = currentSession.createQuery("FROM Klienci WHERE idklienta = :clientId");
            q.setParameter("clientId", clientId);
            client = (Klienci) q.uniqueResult();

            clientBean.setFirstname(client.getImie());
            clientBean.setLastname(client.getNazwisko());
            clientBean.setAddress(client.getAdres());
            clientBean.setPesel(client.getPesel());

            user = client.getUzytkownicy();
            clientBean.setUsername(user.getLogin());
        }
        // Rejestracja nowego klienta.
        else {
            client = new Klienci(); // Encja klienta.
            user = new Uzytkownicy(); // Encja użytkownika.
        }
        
        if (clientBean.isSent()) {
            ActionErrors errors = clientBean.validate(mapping, request);
            
            if (!errors.isEmpty()) {
                saveErrors(request, errors);
                return mapping.findForward("failure");
            }
        } else {
            return mapping.findForward("failure");
        }
        
        // Zapisujemy dane do encji użytkownika.
        user.setLogin(clientBean.getUsername());
        if (clientBean.getPassword() != null && clientBean.getPassword().length() > 0) {
            user.setHaslo(clientBean.getPassword());
        }
        
        // Zapisujemy dane do encji klienta.
        client.setImie(clientBean.getFirstname());
        client.setNazwisko(clientBean.getLastname());
        client.setPesel(clientBean.getPesel());
        client.setAdres(clientBean.getAddress());
        
        // Zapisujemy użytkownika do encji klienta.
        client.setUzytkownicy(user);
        
        currentSession.saveOrUpdate(user);
        currentSession.saveOrUpdate(client);
        currentSession.getTransaction().commit();
        
        return mapping.findForward(SUCCESS);
    }
    
    public ActionForward delete(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // Pobieramy ID klienta z adresu URL.
        String clientId = request.getParameter("clientId");
        Session currentSession = HibernateUtil.getSession();
        currentSession.beginTransaction();
        
        // Pobieramy dane klienta z bazy.
        Query q = currentSession.createQuery("FROM Klienci WHERE idklienta = :clientId");
        q.setParameter("clientId", clientId);
        Klienci client = (Klienci) q.uniqueResult();
        // Usuwamy wybranego klienta.
        currentSession.delete(client);
        currentSession.getTransaction().commit();
        
        ActionRedirect redirect = new ActionRedirect(mapping.findForward("clientsList"));
        return redirect;
    }
}
